import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
// @app/common
import { CommonModule } from '@app/common';
import { AuthModule } from './auth/auth.module';
import { SystemModule } from './system/system.module';
// AuthZModule
import { AuthZModule, AUTHZ_ENFORCER } from 'nest-authz';
import TypeORMAdapter from 'typeorm-adapter';
import * as casbin from 'casbin';
import * as path from 'path';
import { RoleAccessEntity } from './system/role/entities';


@Module({
  imports: [
    CommonModule,
    AuthZModule.register({
      imports: [ConfigModule],
      enforcerProvider: {
        provide: AUTHZ_ENFORCER,
        inject: [ConfigService],
        useFactory: async (configService: ConfigService) => {
          return casbin.newEnforcer(
            path.join(process.cwd(), 'authz-rbac-model.conf'),
            await TypeORMAdapter.newAdapter(
              {
                synchronize: false,
                name: 'system_permission_access',
                type: configService.get<any>('database.type'),
                host: configService.get<string>('database.host'),
                port: configService.get<number | undefined>('database.port'),
                database: configService.get<string>('database.name', 'db'),
                username: configService.get<string>('database.user', 'root'),
                password: configService.get<string>('database.pass', '123456'),
                entityPrefix: configService.get<string>('database.prefix'),
              },
              {
                customCasbinRuleEntity: RoleAccessEntity,
              },
            ),
          );
        },
      },
      userFromContext: (ctx) => {
        const request = ctx.switchToHttp().getRequest();
        return request.user && request.user.id;
      },
    }),
    AuthModule,
    SystemModule,
  ],
  controllers: [],
  providers: [],
})
export class AdminModule {}
